<template>
  <div class="spec-container">
    <!-- 规格输入区域 -->
    <div v-for="(spec, index) in specs" :key="index" class="spec-item">
      <el-form-item label="规格名称：">
        <el-input
          v-model="spec.name"
          size="large"
          placeholder="请输入规格名称"
          :disabled="spec.is_edit"
          @change="generateSkus"
        />
      </el-form-item>

      <el-form-item label="规格值：">
        <div class="spec-values">
          <el-tag
            v-for="(value, vIndex) in spec.values"
            :key="vIndex"
            size="large"
            closable
            @close="removeSpecValue(index, vIndex)"
          >
            {{ value }}
          </el-tag>
          <el-input
            v-model="spec.newValue"
            size="large"
            placeholder="输入后按回车添加"
            @keyup.enter="addSpecValue(index)"
          />
        </div>
      </el-form-item>
      <el-button
        v-if="specs.length > 1"
        type="danger"
        icon="Delete"
        circle
        @click="removeSpec(index)"
      />
    </div>

    <div v-if="specs.length > 0" class="tips-box">
      <p class="skus-tips">示例：</p>
      <p class="skus-tips">规格名称：颜色，规格值：黑色</p>
      <p class="skus-tips">规格名称：尺码，规格值：XL</p>
    </div>

    <!-- 操作按钮 -->
    <el-button type="primary" size="large" @click="addSpec">添加规格</el-button>

    <!-- 生成的SKU列表 -->
    <div v-if="skus.length > 0" class="sku-table">
      <h4>SKU列表</h4>
      <el-table
        :data="quickSkus"
        border
        style="width: 75vw"
        :header-row-style="{ 'background-color': '#f5f6f7', color: '#222', height: '40px' }"
        :header-cell-style="{ 'background-color': '#f5f6f7', color: '#222', height: '40px' }"
      >
        <el-table-column
          v-for="(spec, sIndex) in specs"
          :key="sIndex"
          :label="spec.name"
          align="center"
        >
          <template #default="{ row }">
            <!--            <el-select-->
            <!--              size="large"-->
            <!--              v-model="row['sku_'+(sIndex+1)]"-->
            <!--              clearable-->
            <!--              :placeholder="'选择'+spec.name">-->
            <!--              <el-option-->
            <!--                v-for="(val, index) in spec.values"-->
            <!--                :key="index"-->
            <!--                :label="val"-->
            <!--                :value="val"-->
            <!--              />-->
            <!--            </el-select>-->
          </template>
        </el-table-column>
        <el-table-column label="图片" align="center" width="80">
          <template #default="{ row, $index }">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              name="file"
              :headers="{ Authorization: accessToken }"
              :before-upload="onBeforeUpload"
              :on-success="
                (response, file, fileList) => onUploadSuccess3(response, file, fileList, $index)
              "
              :on-error="onUploadError"
              :show-file-list="false"
            >
              <img v-if="row.image_url" :src="row.image_url" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <CameraFilled />
              </el-icon>
            </el-upload>
          </template>
        </el-table-column>
        <el-table-column label="销售价格">
          <template #default="{ row }">
            <el-input v-model.number="row.sale_price" size="large" type="number" min="0" />
          </template>
        </el-table-column>
        <el-table-column label="成本价格">
          <template #default="{ row }">
            <el-input v-model.number="row.stand_price" size="large" type="number" min="0" />
          </template>
        </el-table-column>
        <el-table-column label="指导价格">
          <template #default="{ row }">
            <el-input v-model.number="row.guiding_price" size="large" type="number" min="0" />
          </template>
        </el-table-column>
        <el-table-column label="体积">
          <template #default="{ row }">
            <el-input v-model.number="row.volume" size="large" type="number" min="0" />
          </template>
        </el-table-column>
        <el-table-column label="重量">
          <template #default="{ row }">
            <el-input v-model.number="row.weight" size="large" type="number" min="0" />
          </template>
        </el-table-column>
        <el-table-column label="库存">
          <template #default="{ row }">
            <el-input v-model.number="row.stock" size="large" type="number" min="0" />
          </template>
        </el-table-column>
        <el-table-column label="条形码">
          <template #default="{ row }">
            <el-input v-model.number="row.barcode" size="large" placeholder="条形码" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" text @click="quickSkusChange">批量修改</el-button>

            <el-switch
              v-model="row.is_active"
              size="large"
              class="ml-2"
              width="60"
              inline-prompt
              active-text="显示"
              inactive-text="隐藏"
            />
          </template>
        </el-table-column>
      </el-table>

      <el-table
        :data="skus"
        :span-method="objectSpanMethod"
        border
        :show-header="false"
        style="width: 75vw"
      >
        <el-table-column
          v-for="(spec, sIndex) in specs"
          :key="sIndex"
          :label="spec.name"
          align="center"
        >
          <template #default="{ row }">
            {{ row[spec.name] }}
          </template>
        </el-table-column>
        <el-table-column label="图片" align="center" width="80">
          <template #default="{ row, $index }">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              name="file"
              :headers="{ Authorization: accessToken }"
              :before-upload="onBeforeUpload"
              :on-success="
                (response, file, fileList) => onUploadSuccess2(response, file, fileList, $index)
              "
              :on-error="onUploadError"
              :show-file-list="false"
            >
              <img v-if="row.image_url" :src="row.image_url" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <CameraFilled />
              </el-icon>
            </el-upload>
          </template>
        </el-table-column>
        <el-table-column label="销售价格">
          <template #default="{ row, $index }">
            <el-input
              v-model.number="row.sale_price"
              size="large"
              type="number"
              min="0"
              @input="headInputChange($event, $index)"
            />
          </template>
        </el-table-column>
        <el-table-column label="成本价格">
          <template #default="{ row, $index }">
            <el-input
              v-model.number="row.stand_price"
              size="large"
              type="number"
              min="0"
              @input="headInputChange($event, $index)"
            />
          </template>
        </el-table-column>
        <el-table-column label="指导价格">
          <template #default="{ row, $index }">
            <el-input
              v-model.number="row.guiding_price"
              size="large"
              type="number"
              min="0"
              @input="headInputChange($event, $index)"
            />
          </template>
        </el-table-column>
        <el-table-column label="体积">
          <template #default="{ row }">
            <el-input v-model.number="row.volume" size="large" type="number" min="0" />
          </template>
        </el-table-column>
        <el-table-column label="重量">
          <template #default="{ row }">
            <el-input v-model.number="row.weight" size="large" type="number" min="0" />
          </template>
        </el-table-column>
        <el-table-column label="库存">
          <template #default="{ row, $index }">
            <el-input
              v-model.number="row.stock"
              size="large"
              type="number"
              min="0"
              @input="headInputChange($event, $index)"
            />
          </template>
        </el-table-column>
        <el-table-column label="条形码">
          <template #default="{ row, $index }">
            <el-input
              v-model.number="row.barcode"
              size="large"
              placeholder="条形码"
              @input="headInputChange($event, $index)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right">
          <template #default="{ row, $index }">
            <el-switch
              v-model="row.is_active"
              size="large"
              class="ml-2"
              width="60"
              inline-prompt
              active-text="显示"
              inactive-text="隐藏"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import type { UploadProps } from "element-plus";

const emits = defineEmits(["skusChange"]);
const props = defineProps({
  uploadUrl: {
    type: String,
    default: "",
  },
  accessToken: {
    type: String,
    default: "",
  },
  attributesData: {
    type: Array,
    default: () => [],
  },
  skuData: {
    type: Array,
    default: () => [],
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
});

// 规格数据结构
const specs = ref([
  {
    name: "",
    values: [],
    newValue: "",
    is_edit: false,
  },
]);

// 快捷设置SKU
const quickSkus = ref([]);
// 生成SKU列表
const skus = ref([]);

const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  const key = specs.value[0]?.name;
  if (columnIndex === 0) {
    // 只对第一个列进行合并
    // 判断当前行的值是否与上一行的值相同
    if (rowIndex > 0 && skus.value[rowIndex][key] === skus.value[rowIndex - 1][key]) {
      return { rowspan: 0, colspan: 1 }; // 合并行
    } else {
      // 计算需要合并的行数
      let rowspan = 1;
      for (let i = rowIndex + 1; i < skus.value.length; i++) {
        if (skus.value[i][key] === skus.value[rowIndex][key]) {
          rowspan++;
        } else {
          break;
        }
      }
      return { rowspan, colspan: 1 };
    }
  }
};

// 添加规格
const addSpec = () => {
  specs.value.push({
    name: "",
    values: [],
    newValue: "",
    is_edit: false,
  });
};

// 删除规格
const removeSpec = (index) => {
  if (specs.value.length <= 1) return;
  specs.value.splice(index, 1);
  generateSkus();
};

// 添加规格值
const addSpecValue = (index) => {
  const value = specs.value[index].newValue.trim();
  if (!value) {
    ElMessage.info("规格值不能为空");
  } else if (value && !specs.value[index].values.includes(value)) {
    specs.value[index].values.push(value);
    specs.value[index].newValue = "";
    generateSkus();
  } else {
    ElMessage.info("该规格值已存在");
  }
};

// 删除规格值
const removeSpecValue = (specIndex, valueIndex) => {
  specs.value[specIndex].values.splice(valueIndex, 1);
  generateSkus();
};

// 生成SKU组合
const generateSkus = () => {
  const validSpecs = specs.value.filter((spec) => spec.name && spec.values.length > 0);
  // 递归生成所有组合
  const combine = (remaining, current = {}, combinations = []) => {
    if (remaining.length === 0) {
      let attributes = [];
      for (let k in current) {
        attributes.push({
          key: k,
          value: current[k],
        });
      }
      combinations.push({
        ...current,
        barcode: "",
        stand_price: 0,
        sale_price: 0,
        guiding_price: 0,
        stock: 0,
        is_active: true,
        image_url: "",
        attributes: attributes,
      });
      return;
    }

    const [first, ...rest] = remaining;
    for (const value of first.values) {
      combine(rest, { ...current, [first.name]: value }, combinations);
    }
    return combinations;
  };
  skus.value = combine(validSpecs) || [];

  let spec_obj = {};
  for (let i = 0; i < specs.value.length; i++) {
    spec_obj["sku_" + (i + 1)] = "";
  }
  quickSkus.value = [
    {
      ...spec_obj,
      barcode: "",
      stand_price: 0,
      sale_price: 0,
      guiding_price: 0,
      stock: 0,
      is_active: true,
      image_url: "",
    },
  ];
};

const onBeforeUpload: UploadProps["beforeUpload"] = (file) => {
  if (file.type != "image/jpeg" && file.type != "image/png") {
    ElMessage.error("图片类型仅支持PNG,JPG！");
    return false;
  } else if (file.size / 1024 / 1024 > 5) {
    ElMessage.error("图片大小不能超过5MB！");
    return false;
  }
  return true;
};

const onUploadSuccess2: UploadProps["onSuccess"] = (response, file, fileList, index) => {
  ElMessage.success("上传成功");
  skus.value[index].image_url = response.url;
};
const onUploadSuccess3: UploadProps["onSuccess"] = (response, file, fileList, index) => {
  ElMessage.success("上传成功");
  quickSkus.value[index].image_url = response.url;
};

const onUploadError: UploadProps["onError"] = (file) => {
  ElMessage.error("上传失败");
  console.log("error==", file);
};

function quickSkusChange() {
  const quick = quickSkus.value[0];
  // const skusData = quickFillSkus(quick, skus.value);
  // console.log(skusData);
  for (let i = 0; i < skus.value.length; i++) {
    skus.value[i].barcode = quick.barcode;
    skus.value[i].stand_price = quick.stand_price;
    skus.value[i].sale_price = quick.sale_price;
    skus.value[i].guiding_price = quick.guiding_price;
    skus.value[i].stock = quick.stock;
    skus.value[i].is_active = quick.is_active;
    skus.value[i].image_url = quick.image_url;
  }
  emits("skusChange", { skus: skus.value, specs: specs.value });
}

// 快速匹配并填充 skus
const quickFillSkus = (quick, skus) => {
  // 生成 skus 的键列表
  const skuKeys = specs.value.map((spec) => spec.name);
  // 动态提取 quick 中的 sku 值（如 sku_1, sku_2）
  const quickSkus = skuKeys.map((_, index) => quick[`sku_${index + 1}`]);

  // 找到匹配的 SKU
  const matchedSkus = skus.filter((sku) =>
    skuKeys.every((key, index) => sku[key] === quickSkus[index])
  );
  if (matchedSkus.length > 0) {
    matchedSkus.forEach((matchedSku) => {
      // 更新匹配的 SKU 字段
      matchedSku.barcode = quick.barcode;
      matchedSku.guiding_price = quick.guiding_price;
      matchedSku.image_url = quick.image_url;
      matchedSku.is_active = quick.is_active;
      matchedSku.sale_price = quick.sale_price;
      matchedSku.stand_price = quick.stand_price;
      matchedSku.stock = quick.stock;
    });
    return matchedSkus;
  } else {
    return false;
  }
};

function headInputChange(e, index) {
  emits("skusChange", { skus: skus.value, specs: specs.value });
}

watch(
  props.attributesData,
  (newVal, oldVal) => {
    if (newVal) {
      specs.value = [];
      newVal.forEach((obj) => {
        specs.value.push({
          name: obj.name,
          values: obj.data,
          newValue: "",
          is_edit: props.isEdit,
        });
      });

      let spec_obj = {};
      for (let i = 0; i < specs.value.length; i++) {
        spec_obj["sku_" + (i + 1)] = "";
      }
      quickSkus.value = [
        {
          ...spec_obj,
          barcode: "",
          stand_price: 0,
          sale_price: 0,
          guiding_price: 0,
          stock: 0,
          is_active: true,
          image_url: "",
        },
      ];
    }
  },
  { deep: true, immediate: true }
);

watch(
  props.skuData,
  (newVal, oldVal) => {
    if (newVal || newVal.length > 0) {
      let data = [];
      newVal.forEach((item) => {
        item.attributes.forEach((item2) => {
          item[item2.key] = item2.value;
        });
        item.barcode = item.barcode === "无" ? "" : item.barcode;
        data.push(item);
      });
      skus.value = data;
    }
  },
  { deep: true, immediate: true }
);
</script>

<style scoped>
.spec-container {
  width: 85vw;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.spec-item {
  display: flex;
  align-items: flex-start;
  gap: 20px;
  margin-bottom: 20px;
}

.spec-values {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.sku-table {
  margin-top: 30px;
}

.el-tag {
  margin-right: 8px;
}

.avatar-uploader .avatar {
  width: 60px;
  height: 60px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader .el-icon.avatar-uploader-icon {
  font-size: 22px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  text-align: center;
}

.tips-box {
  margin-bottom: 10px;
}

.tips-box .skus-tips {
  margin: 0;
  font-size: 14px;
  color: #999999;
  font-weight: bold;
}
</style>
